package com.example.fw;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactData;
import com.example.utils.SortedListOf;


public class ContactHelper extends WebDriverHelperBase{

	public static boolean CREATION = true;
	public static boolean MODIFICATION = false;
	
	public ContactHelper(ApplicationManager manager) {
		super(manager);
	}
	
	public SortedListOf<ContactData> getUiContacts() {
		SortedListOf<ContactData> contacts = new SortedListOf<ContactData>();
		manager.navigateTo().mainPage();
		List<WebElement> rows = driver.findElements(By.xpath("//tr[@name='entry']"));
		for (WebElement row : rows) {
			String firstname = row.findElement(By.xpath("td[3]")).getText();
			String lastname = row.findElement(By.xpath("td[2]")).getText();
			contacts.add(new ContactData().withFirstname(firstname).withLastname(lastname));	
		}
		return contacts;
	}
	
	public SortedListOf<ContactData> getContactsTable() {
		SortedListOf<ContactData> contactsTable = new SortedListOf<ContactData>();
		manager.navigateTo().mainPage();
		List<WebElement> rows = driver.findElements(By.xpath("//tr[@name='entry']"));
		for (int i = 0; i < rows.size(); i++) {
			String firstname = driver.findElement(By.xpath("//tr[@name='entry']["+ (i + 1) + "]/td[3]")).getText();
			String lastname = driver.findElement(By.xpath("//tr[@name='entry']["+ (i + 1) + "]/td[2]")).getText();
			initContactModification(i);
			String home = driver.findElement(By.name("home")).getAttribute("value");
			String mobile = driver.findElement(By.name("mobile")).getAttribute("value");
			String work = driver.findElement(By.name("work")).getAttribute("value");
			contactsTable.add(new ContactData().withFirstname(firstname).withLastname(lastname).withHome(home)
					.withMobile(mobile).withWork(work));	
			click(By.linkText("home"));
		}
		return contactsTable;
	}
	
	public SortedListOf<ContactData> getPrintContacts() {
		SortedListOf<ContactData> printContacts = new SortedListOf<ContactData>();
		manager.navigateTo().printPhonesPage();
		List<WebElement> contacts = driver.findElements(By.xpath("//td[@valign='top']"));
		for (WebElement contact : contacts) {
			String printContact = contact.getText();
			String firstnameAndLastname = printContact.split(":")[0];
			String firstname = "";
			String lastname = "";
			String home = "";
			String mobile = "";
			String work = "";
			
			Pattern onlyFirstname = Pattern.compile("\\s$");
			Pattern onlyLastname = Pattern.compile("^\\S*$");
			
			Matcher matcherOnlyFirstname = onlyFirstname.matcher(firstnameAndLastname);
			Matcher matcherOnlyLastname = onlyLastname.matcher(firstnameAndLastname);
			
			if (matcherOnlyFirstname.find()) {
				firstname = firstnameAndLastname.split(" ")[0];
			} else {
				if (matcherOnlyLastname.find()) {
					lastname = firstnameAndLastname;
				} else {
					if (firstnameAndLastname != "") { 
					String[] buf = firstnameAndLastname.split(" ");
					firstname = buf[0];
					lastname = buf[1];
					}
			    }
			}
			
			Pattern homePhone = Pattern.compile("H: \\d*");
			Pattern mobilePhone = Pattern.compile("M: \\d*");
			Pattern workPhone = Pattern.compile("W: \\d*");

			Matcher matcherHome= homePhone.matcher(printContact);
			Matcher matcherMobile = mobilePhone.matcher(printContact);
			Matcher matcherWork = workPhone.matcher(printContact);
			
			if (matcherHome.find()) {
				home = matcherHome.group().substring(3);
			} 
			
			if (matcherMobile.find()) {
				mobile = matcherMobile.group().substring(3);
			}
			
			if (matcherWork.find()) {
				work = matcherWork.group().substring(3);
			}
			
			printContacts.add(new ContactData().withFirstname(firstname).withLastname(lastname).withHome(home)
					.withMobile(mobile).withWork(work));	
		}
		return printContacts;
	}
	
	public ContactHelper createContact(ContactData contact) {
		initContactCreation();
	    fillContactForm(contact, CREATION);
	    submitContactCreation();
	    returnToMainPage();
	    manager.getModel().addContact(contact);
	    return this;
	}

	public ContactHelper modifyContact(ContactData contact, int index) {
		initContactModification(index);
	    fillContactForm(contact, MODIFICATION);
	    submitContactModification();
	    returnToMainPage();
	    manager.getModel().removeContact(index).addContact(contact);
	    return this;
	}

	public ContactHelper deleteContact(int index) {
		initContactModification(index);
		submitContactDeletion();
		returnToMainPage();
		manager.getModel().removeContact(index);
		return this;
	}
	
	//-------------------------------------------------------------------------------------------------
	
	public ContactHelper initContactCreation() {
		manager.navigateTo().mainPage();
		click(By.linkText("add new"));
		return this;
	}

	public ContactHelper submitContactCreation() {
		click(By.name("submit"));
		return this;
	}

	public ContactHelper fillContactForm(ContactData contact, boolean formType) {
		type(By.name("firstname"),contact.getFirstname());
	    type(By.name("lastname"),contact.getLastname());
	    type(By.name("address"),contact.getAddress());
	    type(By.name("home"),contact.getHome());
	    type(By.name("mobile"),contact.getMobile());
	    type(By.name("work"),contact.getWork());
	    type(By.name("email"),contact.getEmail());
	    type(By.name("email2"),contact.getEmail2());
	    selectByText(By.name("bday"), contact.getBday());
	    selectByText(By.name("bmonth"), contact.getBmonth());
	    if (formType = CREATION) {
	    	selectByText(By.name("new_group"), contact.getGroup());
	    } else {
	    	if (driver.findElements(By.name("new_group")).size() != 0 ) {
	    		throw new Error("Group selector exist in contact modification form");
	    	}
	    }
	    type(By.name("byear"),contact.getByear());
	    type(By.name("address2"),contact.getAddress2());
	    type(By.name("phone2"),contact.getPhone2());
	    return this;
	}

	public ContactHelper initContactModification(int index) {
		manager.navigateTo().mainPage();
		By locator = By.xpath("(//img[@title='Edit'])[" + (index + 1) + "]");
		if (isElementPresent(locator)) {
			click(locator);
		}
		return this;
	}

	public ContactHelper submitContactModification() {
		click(By.xpath("//input[@value='Update']"));
		return this;
	}
	
	private ContactHelper submitContactDeletion() {
		click(By.xpath("//input[@value='Delete']"));
		return this;
	}
	
	private ContactHelper returnToMainPage() {
		click(By.linkText("home page"));
		return this;
	}

	public ContactData getContact(int index) {
		manager.navigateTo().mainPage();
		initContactModification(index);
		String firstname = driver.findElement(By.name("firstname")).getAttribute("value");
		String lastname = driver.findElement(By.name("lastname")).getAttribute("value");
		String address = driver.findElement(By.name("address")).getAttribute("value");
		String home = driver.findElement(By.name("home")).getAttribute("value");
		String mobile = driver.findElement(By.name("mobile")).getAttribute("value");
		String work = driver.findElement(By.name("work")).getAttribute("value");
		String email = driver.findElement(By.name("email")).getAttribute("value");
		String email2 = driver.findElement(By.name("email2")).getAttribute("value");
		String bday = driver.findElement(By.xpath("//*[@name='bday']/*[@selected='selected']")).getText();
		String bmonth = driver.findElement(By.xpath("//*[@name='bmonth']/*[@selected='selected']")).getText();
		String byear = driver.findElement(By.name("byear")).getAttribute("value");
		String address2 = driver.findElement(By.name("address2")).getAttribute("value");
		String phone2 = driver.findElement(By.name("mobile")).getAttribute("phone2");
		ContactData contact = new ContactData().withFirstname(firstname).withLastname(lastname).withAddress(address).withHome(home)
					.withMobile(mobile).withWork(work).withEmail(email).withEmail2(email2).withBday(bday).withBmonth(bmonth)
					.withByear(byear).withAddress2(address2).withPhone2(phone2);	
		return contact;
	}
}
